package com.web.base.open.dao;

import com.blue.jdbc.BaseDao;
import com.web.base.open.model.Role;
import com.web.base.open.model.RoleAccount;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 开放平台角色-帐号数据库访问
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2017年02月27日
 */
@Repository("openRoleAccountDao")
public class RoleAccountDao extends BaseDao<RoleAccount>
{
	public RoleAccountDao()
	{
	}
	
	@Override
	protected void query(StringBuilder sql, RoleAccount param)
	{
		if (param != null)
		{
			if (param.getRoleId() != null && param.getRoleId() > 0)
				sql.append(" and a.role_id=:roleId");
			
			if (param.getAccountId() != null && param.getAccountId() > 0)
				sql.append(" and a.account_id=:accountId");
			
		}
	}

	public void deleteByAccount(Integer accountId)
	{
		String sql = "delete from open_role_account where account_id=?";
		jdbcTemplate.update(sql, accountId);
	}
	
	public List<Integer> listByAccount(Integer accountId)
	{
		String sql = "select role_id from open_role_account where account_id=?";
		List<Integer> list = jdbcTemplate.queryForList(sql, Integer.class, accountId);
		return list;
	}
	
	public List<Integer> listByAccount(String accountName)
	{
		String sql = "select ra.role_id from open_role_account ra, open_account a where ra.account_id=a.id and a.name=?";
		List<Integer> list = jdbcTemplate.queryForList(sql, Integer.class, accountName);
		return list;
	}
	
	public List<Role> listSelect(Integer accountId)
	{
		Map<String, Object> param = new HashMap<>();
		param.put("accountId", accountId);
		String sql = "select r.id, r.name, isnull(ra.role_id) `select` from open_role r"
				+ " left join (select * from open_role_account where account_id=:accountId) ra on ra.role_id=r.id"
				+ " where r.state=0";
		return jdbcObjectTemplate.list(Role.class, sql, param);
	}
	
}
